package com.zzb.weikeautosign.threadpool;

import com.alibaba.fastjson.JSONObject;
import com.zzb.weikeautosign.Constants;
import com.zzb.weikeautosign.Misc;
import com.zzb.weikeautosign.communication.CommuicationUtil;
import com.zzb.weikeautosign.httpexecute.LoginExecute;
import com.zzb.weikeautosign.httpexecute.PraiseExecute;
import com.zzb.weikeautosign.httpexecute.SignInExecute;
import com.zzb.weikeautosign.httpexecute.UserShareListExecute;
import com.zzb.weikeautosign.param.LoginParam;
import com.zzb.weikeautosign.param.PraiseParam;
import com.zzb.weikeautosign.param.SignInParam;
import com.zzb.weikeautosign.param.UserShareListParam;
import com.zzb.weikeautosign.vo.UserShareVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.ArrayUtils;
import org.apache.log4j.Logger;

import java.util.List;

/**
 * 执行线程
 * Created by zzb on 16/1/20.
 */
public class ExcuteThread extends Thread {
    private static final Logger log = Logger.getLogger(ExcuteThread.class);
    JSONObject loginUser;
    String userName;
    String ticket;
    String userId;
    public ExcuteThread(String userName ,String password){
        LoginParam loginParam = new LoginParam(userName,password);
        this.userName = userName;
        //登录
        loginUser = LoginExecute.execute(loginParam);
        log.info(userName+" 登录: "+loginUser.getBoolean("success"));
    }
    public boolean isLoginSuccess(){
        return Misc.isTrue(loginUser.getBoolean("success"));
    }
    @Override
    public void run(){
        if(isLoginSuccess()){
            ticket = loginUser.getString("ticket");
            userId = loginUser.getString("userId");
            SignInParam signInParam = new SignInParam(ticket,userId);
            JSONObject signResult = SignInExecute.execute(signInParam);
            log.info(userName+" 签到: "+signResult);
            log.info(userName + " 正在读取朋友圈列表~~~");
            UserShareListParam userShareListParam = new UserShareListParam(ticket,userId, Constants.LIST_UPDATE);
            JSONObject listResult = UserShareListExecute.execute(userShareListParam);
            log.info(listResult.toJSONString());
            log.info("获取朋友圈未点赞id列表");
            List<String> ids = new UserShareVo(listResult).getUnPaiseList(userId);
            log.info(ArrayUtils.toString(ids.toArray()));
            if(CollectionUtils.isNotEmpty(ids)){
                ids.forEach(id -> {
                    JSONObject praiseResult = PraiseExecute.execute(new PraiseParam(id,ticket,userId));
                    System.out.println(praiseResult);
                });
            }
        }else{
            log.error("用户登录失败!已经移出队列!");
            CommuicationUtil.push(userName,"亲,账号或密码出错了,不告诉我正确账号密码我就工作不了了哦!");
        }
        ThreadQueue.getInstances().removeOldTask(userName,loginUser);

    }

    public final String getUserName() {
        return userName;
    }
}
